package code.util;

import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class RequestExecuteThread implements Runnable {
    ConcurrentLinkedQueue<Map<String, ?>> requestQueue;
    ConcurrentHashMap<String, Boolean> flagMap;

    public RequestExecuteThread(ConcurrentLinkedQueue<Map<String, ?>> requestQueue,
            ConcurrentHashMap<String, Boolean> flagMap) {
        this.requestQueue = requestQueue;
        this.flagMap = flagMap;
    }

    public void run() {
        while (true) {
            // TODO Auto-generated method stub
            Iterator<Map<String, ?>> iterator = requestQueue.iterator();
            while (iterator.hasNext()) {
                try {
                    System.out.println("in thread");
                    Thread.sleep(0l);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                Map<String, ?> map = iterator.next();
                HttpServletRequest request = (HttpServletRequest) map.get("request");
                HttpServletResponse response = (HttpServletResponse) map.get("response");
                String requestFlag = (String) map.get("flag");
//                System.out.println(request.getRequestURI());
//                System.out.println(request.getRequestURL());
//                System.out.println(request.getAttribute("id"));
//                System.out.println(request.getContextPath());
                FilterChain filterChain = (FilterChain) map.get("filterChain");
                try {
                    filterChain.doFilter(request, response);
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (ServletException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                iterator.remove();
                flagMap.put(requestFlag, true);
            }
        }
    }

}
